package modelo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import bean.Conexion;

public class FraseDAO extends ConexionDAO {

	

	public FraseDAO() {
		super();
	}
	
	public void registrar(Frase frase) {
		String cadena= frase.getDescripcion();
		String tiraSQL = "INSERT INTO frase "+
		 				 "(descripcion, nivel) "+
		 				 "VALUES ("+
		 				 "'"+cadena.toUpperCase()+"',"+frase.getNivel()+" )";
		Conexion.ejecutar(tiraSQL);
	}
	
	public void modificar(Frase frase) {
		String cadena= frase.getDescripcion();
		String tiraSQL = "UPDATE frase SET descripcion = '" + cadena.toUpperCase() + "', nivel = " + 
		frase.getNivel() + 
		" WHERE id = " + frase.getId();
		 				 
		Conexion.ejecutar(tiraSQL);
	}
	
	public void eliminar(Frase frase) {
		//String cadena= frase.getDescripcion();
		String tiraSQL = "DELETE FROM frase WHERE id = " + frase.getId();		 				 
		Conexion.ejecutar(tiraSQL);
	}
	
	public List<Frase> consultar() {
		List<Frase> frase = new ArrayList<Frase>();
		String tiraSQL = "SELECT * FROM frase";
		ResultSet resultSet = Conexion.consultar(tiraSQL);		
		try {
			while (resultSet.next()) {
				
				int id = resultSet.getInt("id");
				String descripcion = resultSet.getString("descripcion");
				int nivel = resultSet.getInt("nivel");
				Frase fra = new Frase(id, descripcion, nivel);
				frase.add(fra);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return frase;
	}
	
	public Frase asignarFrase(int nivel) {
		
		Frase fra = null;
		String tiraSQL = "SELECT * FROM frase where nivel = "+ Integer.toString(nivel);
		ResultSet resultSet = Conexion.consultar(tiraSQL);
		
		
		String tiraSQLCount = "SELECT count(id) as cant FROM frase where nivel = "+ Integer.toString(nivel);
		ResultSet resultSetCount = Conexion.consultar(tiraSQLCount);
		int ale=0;
		try {
			
			if (resultSetCount.next()){
				int num = resultSetCount.getInt("cant");
				if (num == 0){
					ale = 0;
				}else
					ale = (int) Math.floor(Math.random()*num);
				
				
				//System.out.println(Integer.toString(num));
				//System.out.println(Integer.toString(ale));
			}
			
			if (resultSet.next()) {
				int i = 0;
				while (i <= ale){
					int id = resultSet.getInt("id");
					String descripcion = resultSet.getString("descripcion");
					int nivell = resultSet.getInt("nivel");
					//System.out.println(descripcion);
					resultSet.next();
					i++;
					fra = new Frase(id, descripcion, nivell);
					
				}
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//System.out.println(fra.getDescripcion());
		return fra;
	}


	
}
